package routers

import (
	"blog/models/mgodb"
	"blog/models/myComment"
	"blog/mySessions"
	"context"
	"fmt"
	"github.com/kataras/iris"
	"github.com/kataras/pio"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"mime/multipart"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"time"
)

//获取路径参数
func Handler(ctx iris.Context) {
	name := ctx.Params().Get("name")
	fmt.Println("----------->", name)
}

//获取静态文件访问次数未完工
func Unit8ToString(temp []uint8) string {
	ba := []byte{0}
	for _, b := range temp {
		ba = append(ba, byte(b))
	}
	tempString := string(ba)
	//fmt.Println("------->",tempString,"<-------")
	res := strings.LastIndex(tempString, "/")
	//fmt.Println(tempString[res:])
	return tempString[res:]
}

//劫持火箭通讯记录
func MyHijack(ctx *pio.Ctx) {
	temp, err := ctx.MarshalValue()
	if err != nil {
		fmt.Println(err)
	}
	tempString := Unit8ToString(temp)
	fmt.Println("劫持火箭通讯记录:", tempString[1:])
}

//获取文件当前路径
func getCurrentPath() string {
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		println(err)
	}
	return strings.Replace(dir, "\\", "/", -1) //将\替换成/
}

//错误处理
func ErrorHandling(ctx iris.Context) {
	ctx.StatusCode(iris.StatusNotFound)
	ctx.Text("not found the router")
}

//文件上传
func uploadImage(ctx iris.Context) {
	ctx.UploadFormFiles("./uploads", beforeSave)
}

//文件存储逻辑
func beforeSave(ctx iris.Context, file *multipart.FileHeader) {
	ip := ctx.RemoteAddr()
	// make sure you format the ip in a way
	// that can be used for a file name (simple case):
	//fmt.Println(ip)
	ip = strings.Replace(ip, ".", "_", -1)
	ip = strings.Replace(ip, ":", "_", -1)
	// no need for more actions, internal uploader will use this
	// name to save the file into the "./uploads" folder.
	file.Filename = ip + "-" + file.Filename
	tempUrl := "http://127.0.0.1:3000/" + file.Filename
	ctx.JSON(iris.Map{"ImgUrl": tempUrl})
}

//文件删除
func deletImage(ctx iris.Context) {
	fmt.Println("进入程序")
	tempValue := ctx.FormValue("fileUrl")
	if tempValue == "" {
		fmt.Println("前端传输是一个空", tempValue)
		return
	}
	res := strings.LastIndex(tempValue, "/")
	//fmt.Println("最后出现 / 的位置 是 ：", res)
	//fmt.Println("需要得到的是 ： ", tempValue[res:])
	absPath, _ := filepath.Abs("./uploads" + tempValue[res:])
	//fmt.Println("当前路径",absPath)
	err := os.Remove(absPath)
	if err != nil {
		fmt.Println(err)
	}
}

// 查找
func findOne(ctx iris.Context) {
	uuid := ctx.FormValue("uuid")
	//fmt.Printf("%T___________________> \n",uuid)
	uid, _ := strconv.Atoi(uuid)
	type blog struct {
		Uuid     int
		Data     string
		Title    string
		Language string
		Content  string
	}
	var result blog
	mgo := mgodb.NewMgo("MainSite", "m12blog")
	mgo.FindOne("uid", uid).Decode(&result)
	ctx.JSON(iris.Map{
		"m12content":  result.Content,
		"m12title":    result.Title,
		"m12data":     result.Data,
		"m12language": result.Language,
	})
	//fmt.Println(result.Content)
}

// 按数据量查找
func CollectionFindDocuments(ctx iris.Context) {
	type blogFind struct {
		M12ID    primitive.ObjectID `bson:"_id"`
		Uid      int
		Data     string
		Title    string
		Language string
		Content  string
	}
	var results []blogFind
	mgo := mgodb.NewMgo("MainSite", "m12blog")
	cur := mgo.CollectionDocuments(0, 100, -1)
	for cur.Next(context.TODO()) {
		var elem blogFind
		err := cur.Decode(&elem)
		if err != nil {
			fmt.Println(err)
		}
		results = append(results, elem)
		//fmt.Println("------ >", elem)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	cur.Close(context.TODO())
	ctx.JSON(results)
}

//评论数据 使用N个助推器
//resultsCom[0].Reply = append(resultsCom[0].Reply, resultsRep)
//resultsCom[0].Reply = append(resultsCom[0].Reply, resultsRep)
//resultsCom[0].Reply = append(resultsCom[0].Reply, resultsRep)
func irisComment(ctx iris.Context) {
	var data []myComment.MongoComment
	var channel = make(chan myComment.Reply)
	var resultsCom []myComment.MongoComment
	var resultsRep []myComment.Reply

	mgoCom := mgodb.NewMgo("MainSite", "Comment")
	mogRep := mgodb.NewMgo("MainSite", "Reply")
	cur := mgoCom.CollectionDocuments(0, 10, 1) //多用户修改函数
	for cur.Next(context.TODO()) {
		var elem myComment.MongoComment
		err := cur.Decode(&elem)
		if err != nil {
			fmt.Println(err)
		}
		floorID := elem.Id

		fmt.Println("我要得到的楼层是", elem.Id)
		go func(id int) {
			fmt.Println("进入协程.")
			var resultsComRep myComment.Reply
			curRep := mogRep.CollectionDocuments(0, 10, 1) //多用户修改函数
			for curRep.Next(context.TODO()) {
				var elemRep myComment.MongoReply
				err := curRep.Decode(&elemRep)
				if err != nil {
					fmt.Println(err)
				}
				resultsComRep = append(resultsComRep, elemRep)

			}
			if err := cur.Err(); err != nil {
				fmt.Println(err)
			}
			fmt.Println("正在像通道里写数据~")
			if resultsComRep != nil {
				channel <- resultsComRep
				fmt.Println(resultsComRep)
			} else {
				channel <- myComment.Reply{}
			}
			curRep.Close(context.TODO())
		}(floorID)
		resultsCom = append(resultsCom, elem)
		resultsRep = append(resultsRep, <-channel)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	cur.Close(context.TODO())
	fmt.Println("楼层读取完毕")
	runtime.Gosched() // 防止主线程跑路
	fmt.Println("所有的字评论。", resultsRep[:1])
	for k, v := range resultsRep[:1] {
		fmt.Println("遍历 Rep K", k)
		fmt.Println("v[k]", v[k])
		for _, v1 := range resultsCom {
			if v[k].Id == v1.Id {
				v1.Reply = v
				fmt.Println(v1.Reply)
				data = append(data, v1)
			} else {
				v1.Reply = myComment.Reply{}
				data = append(data, v1)
			}
		}
	}
	fmt.Println(data)
	ctx.JSON(data)
}

// 评论系统 使用两个助推器
func commentGo(ctx iris.Context) {
	var resultsCom []myComment.MongoComment
	var resultsRep myComment.Reply
	go func() {
		mgoRep := mgodb.NewMgo("MainSite", "Reply")
		curRep := mgoRep.CollectionDocuments(0, 100, 1)
		for curRep.Next(context.TODO()) {
			var elem myComment.MongoReply
			err := curRep.Decode(&elem)
			if err != nil {
				fmt.Println(err)
			}
			resultsRep = append(resultsRep, elem)
		}
	}()
	mgoCom := mgodb.NewMgo("MainSite", "Comment")
	curCom := mgoCom.CollectionDocuments(0, 100, 1)
	for curCom.Next(context.TODO()) {
		var elem myComment.MongoComment
		err := curCom.Decode(&elem)
		if err != nil {
			fmt.Println(err)
		}
		resultsCom = append(resultsCom, elem)
	}
	if err := curCom.Err(); err != nil {
		fmt.Println(err)
	}
	curCom.Close(context.TODO())
	runtime.Gosched()              // 防止主线程跑路
	for k, v := range resultsCom { //先遍历层主
		for _, v1 := range resultsRep { // 在匹配本层回复
			if v.Id == v1.Id {
				resultsCom[k].Reply = append(resultsCom[k].Reply, v1)
			}
		}
		if resultsCom[k].Reply == nil {
			resultsCom[k].Reply = myComment.Reply{}
		}
	}
	//fmt.Println(resultsCom)
	ctx.JSON(resultsCom)
}

// 评论系统 子回复
func replyGo(ctx iris.Context) {
	Id, _ := strconv.Atoi(ctx.FormValue("Id"))               // 楼层id
	CommentId, _ := strconv.Atoi(ctx.FormValue("CommentId")) // 文章id  uid
	FromId, _ := strconv.Atoi(ctx.FormValue("FromId"))
	FromName := ctx.FormValue("FromName")
	FromAvatar := ctx.FormValue("FromAvatar")
	ToId, _ := strconv.Atoi(ctx.FormValue("ToId"))
	ToName := ctx.FormValue("ToName")
	ToAvatar := ctx.FormValue("ToAvatar")
	Date := time.Now().String()[:19]
	Content := ctx.FormValue("Content")
	res := strings.Index(Content, ":")
	Content = Content[res+1:]
	//fmt.Println(":第一次出现的地方",res , Content)
	var reply = myComment.MongoReply{
		Id:         Id,
		CommentId:  CommentId,
		FromId:     FromId,
		FromName:   FromName,
		FromAvatar: FromAvatar,
		ToId:       ToId,
		ToName:     ToName,
		ToAvatar:   ToAvatar,
		Content:    Content,
		Date:       Date,
	}
	//fmt.Println(reply)
	mgo := mgodb.NewMgo("MainSite", "Reply")
	result := mgo.InsertOne(reply)
	fmt.Println(result.InsertedID)
	ctx.JSON(200)
}

//添加数据路由
func CollectionInsertDocuments(ctx iris.Context) {
	mgo := mgodb.NewMgo("MainSite", "m12blog")
	title := ctx.FormValue("title")
	language := ctx.FormValue("label")
	//fmt.Println("language_____", language)
	content := ctx.FormValue("value")
	//fmt.Println("content______", content)
	tempTime := time.Now().String()[:10]
	var (
		results []mgodb.BlogFind
	)
	cur := mgo.CollectionDocuments(0, 1, -1)
	for cur.Next(context.TODO()) { // 返回一个光标
		var elem mgodb.BlogFind
		err := cur.Decode(&elem)
		if err != nil {
			fmt.Println(err)
		}
		results = append(results, elem)
		fmt.Println(elem)
	}
	if err := cur.Err(); err != nil {
		fmt.Println(err)
	}
	cur.Close(context.TODO()) //完成后关闭光标
	temp := int64(results[0].Uid) + 1
	var blog = mgodb.Blog{
		Uid:      temp,
		Title:    title,
		Data:     tempTime,
		Language: language,
		Content:  content,
	}
	result := mgo.InsertOne(blog) //result.InsertedID 为 ObjectID("5cc03f8c15c430bc859d0bed")
	fmt.Println("添加的参数是上一个的id + 1 ", temp)
	ctx.JSON(iris.Map{"mongoID": result.InsertedID}) //{"ID":"5cc03f8c15c430bc859d0bed"}
}

//游客
func passer(ctx iris.Context) {
	//passerId := ctx.FormValue("passer")
	//fmt.Println("passer Id :",passerId)
	sessionId := mySessions.Passer(ctx)
	fmt.Println("sessionId>>>>", sessionId)
}

//灵感选择
func insSelectId(ctx iris.Context) {
	selectNumber := ctx.FormValue("selectNumber")
	ctx.JSON(iris.Map{"temp": selectNumber})
}

//初始化 Vue
func initVue(ctx iris.Context) {

	status := mySessions.Secret(ctx) //验证权限
	ctx.JSON(iris.Map{"m12status": status})
}

// 管理员登录
func userLogin(ctx iris.Context) {
	User := ctx.FormValue("user")
	fmt.Println("登录的账号：", User)
	Password := ctx.FormValue("password")
	mgo := mgodb.NewMgo("MainSite", "Administrators")
	var result mgodb.Administrators
	mgo.FindOne("user", User).Decode(&result)

	fmt.Println("mongo获取到的密码 ", result.Password, " password ", Password)
	if Password == result.Password {
		mySessions.Login(ctx) //管理员控制火箭
		fmt.Println("密码正确》》》》")
		fmt.Println("Administrators password", result.Password)
		ctx.JSON(iris.Map{"m12confirm": true})
	} else {
		ctx.JSON(iris.Map{"m12confirm": false})
	}

}

//blog删除
func deleteBlog(ctx iris.Context) {
	count := ctx.FormValue("count")
	fmt.Println("要删除的数据是：", count)
	countPas, _ := strconv.Atoi(count)
	mgo := mgodb.NewMgo("MainSite", "m12blog")
	temp := mgo.Delete("uid", countPas)
	ctx.JSON(iris.Map{
		"m12Uid": temp,
	})
	fmt.Println("删除 ", temp, "个数据.")
}
